<?php

class CourseController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
       	public $layout='//layouts/column2_green';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'dynamic', 'save', 'addTrainer', 'chooseTemplate', 'trainer', 'user', 'addLeadTrainer', 'deleteTrainerFromCourse', 'addTrainerToCourse', 'addUserToCourse', 'deleteUserFromCourse', 'viewSubModules', 'addModule', 'addSubmoduleToCourse', 'deleteSubModuleFromCourse'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Course;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Course'])) {
                    
                    $count = count($_POST['Course']['center']);
                    
                    for ($i = 0; $i < $count; $i++) {
                        
                        $course = new Course;
                        $course->attributes=$_POST['Course'];
                        
                        $course->center = $_POST['Course']['center'][$i];
                        
                        $criteria=new CDbCriteria;
                        $criteria->select='place, token';  // only select the 'title' column
                        $criteria->condition='name=:name';
                        $criteria->params=array(':name'=>$_POST['Course']['center'][$i]);
                        $central = Central::model()->find($criteria);
                        
                        $course->place = $central->place; 
                        
                        $token = $central->token;
                        
                        // add token to course_nr
                        $course_nr = $token . $course->course_nr;
                        $course->course_nr = $course_nr;
                        
                        $course->save(false);
                    }
                    
                    $this->redirect('admin',array('model'=>$model,));

//                    if ($model->save()) {
//                        $this->redirect(array('update','id'=>$model->course_id));
//                    }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Course']))
		{
			$model->attributes=$_POST['Course'];
			if($model->save())
				$this->redirect(array('update','id'=>$model->course_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Course');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Course('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Course']))
			$model->attributes=$_GET['Course'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Course the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Course::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Course $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='course-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	protected function modelToArray($model) {
	
/* 		$centrals = Central::model()->findAll(); */
		
		$modelArray = array();
		
		foreach($model as $m) {
			$modelArray[$m->id] = $m->name;
		}
		
		return $modelArray;
	}
	
	public function actionDynamic() {
	
		if (isset($_POST['Course']['center'])) {      
            $criteria=new CDbCriteria;
            $criteria->select='place';  // only select the 'title' column
            $criteria->condition='name=:name';
            $criteria->params=array(':name'=>$_POST['Course']['center']);
            $central = Central::model()->find($criteria);

            echo CHtml::tag('div class="control-group"', array(), false, false);
            echo CHtml::tag('label class="control-label" for="Course_place"', array(), false, false);
            echo("Ort </label>");
            echo CHtml::tag('div class="controls"', array(), false, false);
            echo CHtml::tag('input id="Course_place" type="text" maxlength="100" name="Course[place]"', array('value'=>$central->place));
            echo("</input></div></div>");
		} else {
            var_dump($_POST);
		}
	
	}

        protected function getTrainer() {
                $trainer = Trainer::model()->findAll();

                $trainerArray = array();

                foreach($trainer as $t) {
                        $trainerArray[$t->trainer_id] = $t->last_name . ' ' . $t->first_name;
                }

                return $trainerArray;
        }

        public function actionChooseTemplate() {

            // Uncomment the following line if AJAX validation is needed
            // $this->performAjaxValidation($model);

            if(isset($_POST['Course'])) {

                $count = count($_POST['Course']['center']);

                for ($i = 0; $i < $count; $i++) {

                    $course = new Course;
                    $course->attributes=$_POST['Course'];

                    $course->center = $_POST['Course']['center'][$i];

                    $criteria=new CDbCriteria;
                    $criteria->select='place, token';  // only select the 'title' column
                    $criteria->condition='name=:name';
                    $criteria->params=array(':name'=>$_POST['Course']['center'][$i]);
                    $central = Central::model()->find($criteria);

                    $course->place = $central->place; 

                    $token = $central->token;

                    // add token to course_nr
                    $course_nr = $token . $course->course_nr;
                    $course->course_nr = $course_nr;

                    $course->save(false);
                }

                $model=new Course;
                $this->redirect('admin',array('model'=>$model,));

//                    if ($model->save()) {
//                        $this->redirect(array('update','id'=>$model->course_id));
//                    }
		
            } else {
                if (isset($_POST['Coursetemplate'])) {

                    // get the model
                    $model = Coursetemplate::model()->find('title=:title', array(':title'=>$_POST['Coursetemplate']['title']));

                    // create a course and assign the values from the template model
                    $course = new Course;
                    $course->category1 = $model->category1;
                    $course->category2 = $model->category2;
                    $course->type = $model->type;
                    $course->title = $model->title;
                    $course->requirement = $model->requirement;
                    $course->content = $model->content;
                    $course->description = $model->description;
                    $course->duration = $model->duration;
                    $course->ue = $model->ue;
                    $course->min_participants = $model->min_participants;
                    $course->max_participants = $model->max_participants;
                    $course->price = $model->price;
                    $course->class_time = $model->class_time;
                    $course->graduation = $model->graduation;
                    $course->statistics = $model->statistics;

                    // render course/create
                    $this->render('create',array('model'=>$course));	

                } else {
                    $Criteria = new CDbCriteria();
                    $Criteria->order = "title ASC";
                    $model = Coursetemplate::model()->findAll($Criteria);

                    $this->render('chooseTemplate',array('model'=>$model));	
                }		
            }
        
        }

        public function actionTrainer($id) {            
            $this->render('viewAndAddTrainer',array('id'=>$id));
        }
        
        public function actionUser($id) {
            $this->render('viewAndAddUser',array('id'=>$id));           
        }
        
//        private function getCourseGiven($course_id, $isLeadTrainer) {
//            $criteria = new CDbCriteria;
//
//            if ($isLeadTrainer) {
//                $conditions = array(
//                    'course_id=:course_id',
//                    'is_lead_trainer=1',
//                );
//                
//                $criteria->condition=implode(' AND ',$conditions);
//
//                $criteria->params=array(':course_id'=>$course_id);
//
//                return CourseGiven::model()->find($criteria);
//            } else {
//
//            }
//        }
        
        protected function getLeadTrainerForCourse($course_id) {
            $course = Course::model()->findByPk($course_id);
            $leadTrainer = Trainer::model()->findByPk($course->lead_trainer);
            
            if ($leadTrainer != NULL) {
                return $leadTrainer;
            } else {
                // no lead trainer set
                return NULL;
            }
        }
        
        protected function getLeadTrainerDropdownArrayForCourse($course_id) {
            
            $leadTrainer = $this->getLeadTrainerForCourse($course_id);
                
            $trainer = $this->getTrainer();
            asort($trainer);
            
            if ($leadTrainer != NULL) {
                $trainerArray = array();
                $trainerArray[$leadTrainer->trainer_id] = $leadTrainer->last_name . " " . $leadTrainer->first_name;
                

                // the lead trainer should be the first element of the drop down list
                return $trainerArray + array(0 => "") + $trainer;
            } else {
                // if no lead trainer is set the first element of the drop down list should be empty
                return array(0 => "") + $trainer;
            }
        }
        
        protected function deleteLeadTrainerForCourse($course_id) {
            
            $conditions = array(
                'course_id=:course_id',
                'is_lead_trainer=1',
            );
            
            $params = array(':course_id'=>$course_id);
            
            $condition=implode(' AND ',$conditions);
            
            CourseGiven::model()->deleteAll($condition, $params);
            
            $this->render('viewAndAddTrainer',array('id'=>$course_id));
        }
        
        public function actionAddLeadTrainer($course_id) {
            $course = Course::model()->findByPk($course_id);
            $course->lead_trainer = $_POST['Trainer']['trainer_id'];
            $course->save();
        }
        
        public function actionDeleteTrainerFromCourse($trainer_id, $course_id) {
             $conditions = array(
                'course_id=:course_id',
                'trainer_id=:trainer_id',
            );
             
             $params = array(':course_id' => $course_id,
                             ':trainer_id' => $trainer_id);
             $condition=implode(' AND ',$conditions);
             
            if (CourseGiven::model()->deleteAll($condition, $params)) {
                $this->render('viewAndAddTrainer',array('id'=>$course_id));
            }
        }
        
        public function actionAddTrainerToCourse($trainer_id, $course_id) {

            // filtering
            $model=new Trainer('search');
            $model->unsetAttributes();  // clear any default values
            if(isset($_GET['Trainer'])) {
                    $model->attributes=$_GET['Trainer'];
            }

            if ($trainer_id == null) {
                $this->render('addTrainer',array('id'=>$course_id, 'model'=>$model));
            } else {     
                // create course_given
                $course_given = new CourseGiven;
                $course_given->trainer_id = $trainer_id;
                $course_given->course_id = $course_id;
                
                if ($course_given->save()) {
                    $this->render('viewAndAddTrainer',array('id'=>$course_id, 'model'=>$model));
                }
                
            }
        }
        
        private function addUserToSubmodules($user_id, $course_id) {
            $course = Course::model()->findByPk($course_id);
            
            if (count($course->children) > 0) {
                // add User to all submodules
                foreach($course->children as $submodule) {
                    $course_taken = new CourseTaken;
                    $course_taken->user_id = $user_id;
                    $course_taken->course_id = $submodule->course_id;
                    $course_taken->save();
                }
            }
        }
        
        public function actionAddUserToCourse($user_id, $course_id) {
                
            // filtering
            $model=new User('search');
            $model->unsetAttributes();  // clear any default values
            
            if(isset($_GET['User'])) {      
                    $model->attributes=$_GET['User'];
            }
            
            if ($user_id == null) {
                $this->render('addUser', array('id'=>$course_id, 'model'=>$model));
            } else {     
                
                $this->addUserToSubmodules($user_id, $course_id);
                
                
                // TODO: wenn der teilnehmer schon zugebucht ist, darf er nicht noch einmal zugebucht werden
                
                
                // create course_taken
                $course_taken = new CourseTaken;
                $course_taken->user_id = $user_id;
                $course_taken->course_id = $course_id;
                
                if ($course_taken->save()) {
                    $this->render('viewAndAddUser',array('id'=>$course_id, 'model'=>$model));
                }
                
            }            
        }
        
        private function deleteUserFromSubmodules($user_id, $course_id) {
            $course = Course::model()->findByPk($course_id);
            
            if (count($course->children) > 0) {
                // delete user from all submodules
                foreach($course->children as $submodule) {
                    
                    $conditions = array(
                        'course_id=:course_id',
                        'user_id=:user_id',
                    );

                     $params = array(':course_id' => $submodule->course_id,
                                     ':user_id' => $user_id);
                     $condition=implode(' AND ',$conditions);
                    
                     CourseTaken::model()->deleteAll($condition, $params);
                }
            }
        }


        public function actionDeleteUserFromCourse($user_id, $course_id) {
            
            $this->deleteUserFromSubmodules($user_id, $course_id);
            
            $conditions = array(
                'course_id=:course_id',
                'user_id=:user_id',
            );
             
             $params = array(':course_id' => $course_id,
                             ':user_id' => $user_id);
             $condition=implode(' AND ',$conditions);
             
            if (CourseTaken::model()->deleteAll($condition, $params)) {
                $this->render('viewAndAddUser',array('id'=>$course_id));
            }
        }
        
        public function actionViewSubModules($id) {

            $model=new Course('search');
            $model->unsetAttributes();  // clear any default values
            if(isset($_GET['Course']))
                    $model->attributes=$_GET['Course'];
                    // only search for modules
//                    $model->is_module = 1;

            $this->render('subModules',array(
                    'model'=>$model,
                    'id'=>$id,
            ));     
            
        }
        
        public function actionAddSubmoduleToCourse($id) {

            if (isset($_POST['autoId'])) {
   
                $count = count($_POST['autoId']);
            
//                // get all selected modules
                for ($i = 0; $i < $count; $i++) {
                    $submodule = new Submodule;
                    $submodule->child_id = $id;
                    $submodule->parent_id = $_POST['autoId'][$i];
                    $submodule->save();
                }
                
                $model = Course::model();
                $this->render('subModules',array(
                    'model'=>$model,
                    'id'=>$id,
                ));  
            } 
        }
        
        public function actionDeleteSubModuleFromCourse($module_id, $course_id) {
            $conditions = array(
                'parent_id=:parent_id',
                'child_id=:child_id',
            );
             
             $params = array(':parent_id' => $module_id,
                             ':child_id' => $course_id);
             $condition=implode(' AND ',$conditions);
            
             if (Submodule::model()->deleteAll($condition, $params)) {
                $model = Course::model();
                $this->render('subModules',array(
                    'model'=>$model,
                    'id'=>$course_id,
                ));     
             }
            
        }
                
}